package com.huifer.wgx.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;

/**
 * <p>Title : JsonUtil </p>
 * <p>Description : jackson 序列化和反序列化</p>
 *
 * @author huifer
 * @date 2019-03-18
 */
public class JsonUtil {

    /**
     * mapper
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 对象转字符串
     * @param data 对象
     * @return json字符串
     */
    public static String obj2Json(Object data) {
        String s = null;
        try {
            s = MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * json 字符串转换对象
     * @param json json字符串
     * @param pojo 实体类
     * @param <T>  对象
     * @return pojo对象
     */
    public static <T> T json2Pojo(String json, Class<T> pojo) {
        T t = null;
        try {
            t = MAPPER.readValue(json, pojo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    /***
     * json 转换成pojo对象列表
     * @param json  json字符串
     * @param pojo 实体类
     * @param <T> 对象
     * @return pojo对象列表
     */
    public static <T> List<T> json2list(String json, Class<T> pojo) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, pojo);
        List<T> list = null;
        try {
            list = MAPPER.readValue(json, javaType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

}
